<template>
  <q-page style="min-height: 88vh">
    <div
      style="width: 100%"
      class="full-height-center row q-gutter-md justify-center items-start"
    >
      <!-- 左侧图像展示区域 -->
      <div class="col-6">
        <q-card flat bordered class="q-pa-md shadow-2">
          <q-img
            :src="imageUrl"
            alt="Generated Plot"
            class="q-mb-md full-width"
            spinner-color="primary"
            style="height: auto; object-fit: contain"
          />
          <!-- 下载图标 -->
          <div class="text-center">
            <q-icon
              name="download"
              size="24px"
              color="primary"
              @click="downloadImage"
              class="download-icon"
            />
            <q-tooltip anchor="bottom middle" self="bottom middle">
              下载图像
            </q-tooltip>
          </div>
        </q-card>
      </div>

      <!-- 右侧参数调整区域 -->
      <div class="col-5">
        <q-card flat bordered class="q-pa-md shadow-2">
          <q-form @submit.prevent="updatePlot" class="q-mt-md">
            <q-input
              v-model="formData.title"
              label="图表标题"
              outlined
              dense
              class="q-mb-sm"
            />
            <q-input
              v-model="formData.x_label"
              label="X 轴标签"
              outlined
              dense
              class="q-mb-sm"
            />
            <q-input
              v-model="formData.y_label"
              label="Y 轴标签"
              outlined
              dense
              class="q-mb-sm"
            />
            <q-input
              v-model="formData.x_ticks_count"
              type="number"
              label="X 轴刻度数"
              outlined
              dense
              class="q-mb-sm"
            />
            <q-input
              v-model="formData.y_ticks_count"
              type="number"
              label="Y 轴刻度数"
              outlined
              dense
              class="q-mb-sm"
            />

            <!-- 标签、颜色、线型和线宽选择区域 -->
            <div
              v-for="(label, index) in formData.labels"
              :key="index"
              class="q-mb-sm row items-center q-gutter-sm"
            >
              <q-input
                v-model="formData.labels[index]"
                label="标签"
                outlined
                dense
                class="col"
              />
              <q-select
                v-model="formData.colors[index].value"
                :options="colorOptions"
                @update:model-value="updateColor(index)"
                label="颜色选择"
                outlined
                dense
                map-options
                emit-value
                class="col"
                style="
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
              />
              <q-select
                v-model="formData.line_styles[index]"
                :options="lineStylesOptions"
                label="线型"
                outlined
                dense
                map-options
                emit-value
                style="
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
                class="col"
              />
              <q-select
                v-model="formData.line_widths[index]"
                :options="lineWidthsOptions"
                label="线宽"
                outlined
                dense
                map-options
                emit-value
                class="col"
              />
            </div>

            <q-btn
              label="更新图像"
              type="submit"
              color="primary"
              unelevated
              class="full-width q-mt-md"
            />
          </q-form>
        </q-card>
      </div>
    </div>
  </q-page>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { createDrawing } from "src/api/api";

import {
  defaultColors,
  colorOptions,
  lineStylesOptions,
  lineWidthsOptions,
} from "src/models/DrawingModel.js";

// 接收父组件传递的 props
const props = defineProps({
  project_id: {
    type: [Number,String],
    required: true,
    default: 2,
  },
  file_id: {
    type: [Number,String],
    required: true,
    default: 7,
  },
  xlsx_name: {
    type: String,
    required: true,
    default: "plotdata_01",
  },
});

const imageUrl = ref(""); // 图像 URL
const formData = ref({
  project_id: props.project_id,
  file_id: props.file_id,
  xlsx_name: props.xlsx_name,
  title: "",
  x_label: "",
  y_label: "",
  x_ticks_count: 5,
  y_ticks_count: 5,
  labels: [],
  colors: [],
  line_styles: [],
  line_widths: [],
  is_save_image: true,
});

// 如果 `project_id`, `file_id` 或 `xlsx_name` 更改，则自动更新
watch(
  () => [props.project_id, props.file_id, props.xlsx_name],
  ([newProjectId, newFileId, newXlsxName]) => {
    formData.value.project_id = newProjectId;
    formData.value.file_id = newFileId;
    formData.value.xlsx_name = newXlsxName;
    initializePlot(); // 重新初始化图像
  }
);

// 生成浅色版本的函数
const lightenColor = (color, percentage = 0.5) => {
  const num = parseInt(color.replace("#", ""), 16);
  const r = (num >> 16) + Math.round((255 - (num >> 16)) * percentage);
  const g =
    ((num >> 8) & 0x00ff) +
    Math.round((255 - ((num >> 8) & 0x00ff)) * percentage);
  const b =
    (num & 0x0000ff) + Math.round((255 - (num & 0x0000ff)) * percentage);
  return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, "0")}`;
};

// 更新颜色选择
const updateColor = (index) => {
  const selectedColor = formData.value.colors[index].value;
  const colorOption = colorOptions.find(
    (option) => option.value === selectedColor
  );

  // 若 colorOption 存在且具有对应的 defaultColors 索引，则使用 defaultColors 中的 region 值
  if (colorOption && typeof colorOption.index !== "undefined") {
    formData.value.colors[index].region =
      defaultColors[colorOption.index].region;
  } else {
    // 若不是 defaultColors 中的颜色，生成浅色版本
    formData.value.colors[index].region = lightenColor(selectedColor);
  }
};

// 初始化获取图像和参数
const initializePlot = async () => {
  try {
    const { data } = await createDrawing({
      ...formData.value,
      title: undefined,
      x_label: undefined,
      y_label: undefined,
      labels: undefined,
      colors: undefined,
      line_styles: undefined,
      line_widths: undefined,
      is_save_image: undefined,
    });
    imageUrl.value = import.meta.env.VITE_BACKEND_URL + data.image_path; // 更新图像 URL
    formData.value = {
      ...formData.value,
      title: data.params.title || "",
      x_label: data.params.x_label || "",
      y_label: data.params.y_label || "",
      labels: data.params.labels || [],
      colors: data.params.labels.map((_, idx) => ({
        value: colorOptions[idx % colorOptions.length].value,
        region: lightenColor(colorOptions[idx % colorOptions.length].value),
      })),
      line_styles: data.params.labels.map(() => lineStylesOptions[0].value),
      line_widths: data.params.labels.map(() => lineWidthsOptions[0].value),
    };
  } catch (error) {
    console.error("Failed to initialize plot:", error);
  }
};

// 点击更新时带参数调用
const updatePlot = async () => {
  try {
    const { data } = await createDrawing(formData.value);
    const cacheBuster = `?cb=${new Date().getTime()}`;
    imageUrl.value = import.meta.env.VITE_BACKEND_URL + data.image_path + cacheBuster;
  } catch (error) {
    console.error("Failed to update plot:", error);
  }
};

// 下载图像
// 下载图像
const downloadImage = () => {
  const link = document.createElement("a"); // 创建一个链接元素
  link.href = imageUrl.value; // 将链接的 href 设置为图像的 URL
  link.setAttribute("download", "plot_image.png"); // 设置下载文件的名称

  document.body.appendChild(link); // 将链接添加到 DOM 中
  link.click(); // 模拟点击以开始下载
  document.body.removeChild(link); // 下载后移除链接
};

// 在组件挂载时获取初始图像
onMounted(() => {
  initializePlot();
});
</script>

<style scoped>
.full-height-center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88vh;
}

.q-img {
  width: 100%;
  object-fit: contain;
}

.q-page {
  background-color: #f5f5f5;
}

.q-card {
  border-radius: 12px;
}

.shadow-2 {
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
}

.download-icon {
  cursor: pointer;
  margin-top: 8px;
}
</style>
